package com.controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.Record;
import com.model.Users;
import com.service.UsersService;

import java.sql.Connection;
import java.sql.Statement;
import java.util.List;

public class UsersController extends Controller {

    private final UsersService service = new UsersService();

    public void index() {
        render("users.jsp");
    }

    /**
     * 查询用户信息并以JSON格式返回
     */
    public void getUsersToJson() {
        String str = service.map2Json(this);
        renderJson(str);
    }

    /**
     * 删除用户信息
     */
    public void deleteUser() {
        Object[] obj = service.deleteUsers(this);
        renderJson(obj);
    }

    /**
     * 编辑用户信息
     */
    public void editUser() {
        getModel(Users.class).update();
        render("/users");
    }

    /**
     * 添加用户信息
     */
    public void addUser() {
        getModel(Users.class).save();
        render("/users");
    }

    /**
     * 还原数据
     */
    public void rowBackUser() {
        String s = "select * from users";
        List<Record> list = Db.find(s);
        if (list != null && list.size() > 0) {
            // 有数据就不要还原
            render("/users");
            return;
        }
        try {
            Connection con = DbKit.getConfig().getConnection();
            Statement st = con.createStatement();
            for (int i = 0; i < 5; i++) {
                String sql = "INSERT INTO users(username,userage,useraddress) VALUES('唐三藏',100,'东土大唐')";
                st.execute(sql);
                sql = "INSERT INTO users(username,userage,useraddress) VALUES('孙悟空',90,'花果山')";
                st.execute(sql);
                sql = "INSERT INTO users(username,userage,useraddress) VALUES('猪八戒',80,'高老庄')";
                st.execute(sql);
                sql = "INSERT INTO users(username,userage,useraddress) VALUES('沙悟净',70,'流沙河')";
                st.execute(sql);
                sql = "INSERT INTO users(username,userage,useraddress) VALUES('白龙马',50,'东海龙宫')";
                st.execute(sql);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        render("/users");
    }
}
